/**
 * GWT Kad : Kademlia implementation for GWT
 * Copyright (C) 2012  Pierrick HYMBERT, Paul-André MISTRAL, Florian ALEXANDRE
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.kad.gwt.web.client.applet.internal.services;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Logger.
 * 
 * @author Pierrick HYMBERT &lt;pierrick [dot] hymbert [at] gmail [dot] com&gt;
 */
public class Logger {
    /**
     * The date format.
     */
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
    /**
     * The file writer.
     */
    private BufferedWriter writer;
    
    /**
     * Constructor.
     */
    public Logger() {
        try {
            writer = new BufferedWriter(new FileWriter(new File(System.getProperty("java.io.tmpdir"), "gwtkad.log")));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * Close the logger and associated resources.
     */
    public void close() {
        try {
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * Log a debug message.
     *
     * @param message The message to log
     */
    public void debug(String message) {
        log("DEBUG", message);
    }
    /**
     * Log an info message.
     *
     * @param message The message to log
     */
    public void info(String message) {
        log("INFO", message);
    }
    /**
     * Log an error message.
     *
     * @param message The message to log
     */
    public void error(String message) {
        log("ERROR", message);
    }

    /**
     * Log a message of the target level.
     *
     * @param level The log level
     * @param message The message
     */
    private void log(String level, String message) {
        try {
            if (writer != null) {
                writer.append(simpleDateFormat.format(new Date()) + " - " + level + " - " + message + "\n");
                writer.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
